package pers.cz.logtail.enums;

import pers.cz.exception.ErrorCode;
import pers.cz.exception.LogSaveException;
import pers.cz.logtail.handle.adapter.LogSave;

public enum SavePlanEnum {
    ;
    /**
     * 持久化方案
     */
    String savePlanName;

    Class<? extends LogSave> logSaveClass;

    SavePlanEnum(String savePlanName, Class<? extends LogSave> logSaveClass) {
        this.savePlanName = savePlanName;
        this.logSaveClass = logSaveClass;
    }

    public String getSavePlanName() {
        return savePlanName;
    }

    public Class<? extends LogSave> getLogSaveClass() {
        return logSaveClass;
    }

    public static Class<? extends LogSave> getLogSaveClassByPlanName(String savePlanName) {

        SavePlanEnum nodeTypeEnum = getEnumBySavePlanName(savePlanName);

        if (nodeTypeEnum == null) {
            throw new LogSaveException(ErrorCode.SAVE_PLAN_ENUM_IS_NULL_ERROR, savePlanName);
        }
        return nodeTypeEnum.getLogSaveClass();
    }

    public static SavePlanEnum getEnumBySavePlanName(String savePlanName) {
        for (SavePlanEnum anEnum : values()) {
            if (anEnum.getSavePlanName().equalsIgnoreCase(savePlanName)) {
                return anEnum;
            }
        }
        return null;
    }

    public static LogSave getLogSaveInstance(String savePlanName) {

        Class<? extends LogSave> nodeClassByNodeName = getLogSaveClassByPlanName(savePlanName);
        LogSave logSave = null;
        try {
            logSave = nodeClassByNodeName.getConstructor().newInstance();
        } catch (Exception e) {
            //e.printStackTrace();
            throw new LogSaveException(ErrorCode.SAVE_PLAN_IMPL_IS_NULL_ERROR, savePlanName);
        }

        return logSave;
    }
}
